﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Components_ProductDetail : System.Web.UI.UserControl
{
    DatabaseHelper helper;
    public static string url;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Page.RouteData.Values["Param"] != null)
            {
                string ProductID = Server.HtmlEncode(Utils.KillChars(Page.RouteData.Values["Param"].ToString()));
                fillDataByProductID(ProductID);
                //Load san pham cung loai
                SimilarProduct(ProductID);

                //Lay URL chia se ban be
                url = Request.Url.ToString();
            }
            else div_main.InnerHtml = "<B>Không tìm thấy sản phẩm</B>";
        }
    }
    private void fillDataByProductID(string strProductID)
    {
        try{
            helper = new DatabaseHelper();
            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "IsNew";
            paramType.DbType = DbType.String;
            paramType.Value = "2";
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramProvinceID = helper.Parameter;
            paramProvinceID.ParameterName = "ProvinceID";
            paramProvinceID.DbType = DbType.Int32;
            paramProvinceID.Value = Convert.ToInt32(Session["ProvinceID"]);
            helper.AddParameter(paramProvinceID);

            System.Data.Common.DbParameter paramProductID = helper.Parameter;
            paramProductID.ParameterName = "ProductID";
            paramProductID.DbType = DbType.Int32;
            paramProductID.Value = Convert.ToInt32(strProductID);
            helper.AddParameter(paramProductID);
            DataTable dt = helper.ExecuteDataTable("Web_GetProduct", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            if (dt.Rows.Count > 0)
            {
                img.ImageUrl = Utils.getUrlImage() + dt.Rows[0]["ImagePath"].ToString();
                lblProductName.Text = dt.Rows[0]["ProductName"].ToString();
                lblProductTypeName2.Text = dt.Rows[0]["ProductTypeName2"].ToString();
                lblPrice.Text = String.Format("{0:N0}", dt.Rows[0]["Price"]);
                lhProductTypeName.Text = dt.Rows[0]["ProductTypeName"].ToString();
                p_content.InnerHtml = dt.Rows[0]["Content"].ToString();
                ViewState["ListProduct"] = dt.Rows[0]["ProductID"] + "@" + dt.Rows[0]["ProductName"] + "@" + dt.Rows[0]["ProductCode"] + "@" + dt.Rows[0]["ImagePath"] + "@" + dt.Rows[0]["Price"] + "@" + dt.Rows[0]["IsPromotion"];
            }
            else {
                div_main.InnerHtml = "<B>Không tìm thấy gạo cần tìm</B>";
                ViewState["ListProduct"] = null;
            }


        }
        catch(Exception ex)
        {
            ControlUtil.LogError("ProductDetail:" + ex.Message);
        }
    }
    private void SimilarProduct(string strProductID)
    {
        try
        {
            helper = new DatabaseHelper();
            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "IsNew";
            paramType.DbType = DbType.String;
            paramType.Value = "3";
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramProvinceID = helper.Parameter;
            paramProvinceID.ParameterName = "ProvinceID";
            paramProvinceID.DbType = DbType.Int32;
            paramProvinceID.Value = Convert.ToInt32(Session["ProvinceID"]);
            helper.AddParameter(paramProvinceID);

            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = 4;
            helper.AddParameter(paramPageSize);

            System.Data.Common.DbParameter paramProductID = helper.Parameter;
            paramProductID.ParameterName = "ProductID";
            paramProductID.DbType = DbType.Int32;
            paramProductID.Value = Convert.ToInt32(strProductID);
            helper.AddParameter(paramProductID);
            DataTable dt = helper.ExecuteDataTable("Web_GetProduct", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            if (dt.Rows.Count > 0)
            {
                lvProductSimilar.DataSource = dt;
                lvProductSimilar.DataBind();
            }
            else
                div_Similar.Style["Display"] = "None";


        }
        catch (Exception ex)
        {
            ControlUtil.LogError("ProductDetail-Similar Product:" + ex.Message);
        }
    }
    protected void btnOrderSimilar_Command(object sender, CommandEventArgs e)
    {
        try
        {
            if (e.CommandArgument != null)//Dat hang
            {
                /*TODO*/
                string str = e.CommandArgument.ToString();

                string[] arrListProduct = str.Split('@');
                int iProductID = Convert.ToInt32(arrListProduct[0]);
                string strProductName = arrListProduct[1];
                string strProductCode = arrListProduct[2];
                string strImagePath = arrListProduct[3];
                double dPrice = Convert.ToDouble(arrListProduct[4]);
                int iWeight = 1;
                string strIsPromotion = arrListProduct[5];
                createCartTable(iProductID, strProductName, strProductCode, strImagePath, dPrice, iWeight, Convert.ToInt32(strIsPromotion));
                Response.Redirect(Request.UrlReferrer.AbsolutePath, false);
            }
            else
            {
                /*TODO*/
                ControlUtil.LogError("Error Add To Cart Page ProductDetail");
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Error Add To Cart Page ProductDetail:" + ex.Message.ToString());
        }
    }
    #region Custom Method
    private void createCartTable(int iProductID, string strProductName, string strProductCode, string strImagePath, double dPrice, int iWeight, int IsPromomtion = 1)
    {
        try
        {
            DataTable dt;
            if (Session["ShoppingCart"] == null)//chua ton tai san pham trong Shopping Cart
            {
                dt = new DataTable();
                dt.Columns.Add("ProductID", System.Type.GetType("System.Int32"));
                dt.Columns.Add("IsPromotion", System.Type.GetType("System.Int32"));
                dt.Columns.Add("ProductName", System.Type.GetType("System.String"));
                dt.Columns.Add("ProductCode", System.Type.GetType("System.String"));
                dt.Columns.Add("ImagePath", System.Type.GetType("System.String"));
                dt.Columns.Add("Price", System.Type.GetType("System.Double"));
                dt.Columns.Add("Weight", System.Type.GetType("System.Int32"));
                dt.Columns.Add("Amount", System.Type.GetType("System.Double"));

                DataRow drNew = dt.NewRow();
                drNew["ProductID"] = iProductID;
                drNew["IsPromotion"] = IsPromomtion;
                drNew["ProductName"] = strProductName.Trim();
                drNew["ProductCode"] = strProductCode.Trim();
                drNew["ImagePath"] = strImagePath.Trim();
                drNew["Price"] = dPrice;
                drNew["Weight"] = iWeight;
                drNew["Amount"] = iWeight * dPrice;
                dt.Rows.Add(drNew);
            }
            else//Da co san pham trong ShoppingCart
            {
                dt = (DataTable)Session["ShoppingCart"];
                if (dt.Select("ProductID=" + iProductID).Count() > 0)//Chi thay doi Shopping Cart cua san pham da ton tai
                {
                    DataRow[] rowArr = dt.Select("ProductID=" + iProductID);
                    if (rowArr.Count() > 0)
                    {
                        DataRow row = rowArr[0];
                        row["Weight"] = Convert.ToInt32(row["Weight"].ToString().Replace(",", "")) + iWeight;//tang trong luong len 1
                        row["Amount"] = Convert.ToDouble(row["Amount"]) + (Convert.ToDouble(row["Price"]) * iWeight);//tinh lai thanh tien
                    }
                }
                else
                {
                    DataRow drNew = dt.NewRow();
                    drNew["ProductID"] = iProductID;
                    drNew["IsPromotion"] = IsPromomtion;
                    drNew["ProductName"] = strProductName.Trim();
                    drNew["ProductCode"] = strProductCode.Trim();
                    drNew["ImagePath"] = strImagePath.Trim();
                    drNew["Price"] = dPrice;
                    drNew["Weight"] = iWeight;
                    drNew["Amount"] = iWeight * dPrice;
                    dt.Rows.Add(drNew);
                }

            }
            Session["ShoppingCart"] = dt;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("CreateTable Shopping Cart Page ProductDetail:" + ex.Message.ToString());
        }
        //return dt;
    }
    #endregion End Custom Method
    //protected void btnOrder_Click(object sender, EventArgs e)
    //{
        
    //    try
    //    {
    //        if (e.CommandArgument != null)//Dat hang
    //        {
    //            string str = e.CommandArgument.ToString();
    //            string[] arrListProduct = str.Split('@');
    //            int iProductID = Convert.ToInt32(arrListProduct[0]);
    //            string strProductName = arrListProduct[1];
    //            string strProductCode = arrListProduct[2];
    //            string strImagePath = arrListProduct[3];
    //            double dPrice = Convert.ToDouble(arrListProduct[4]);
    //            int iWeight = Convert.ToInt32(Server.HtmlDecode(txtWeight.Text.Trim().ToString().Replace(",", "") == "" ? "0" : txtWeight.Text.Trim().ToString().Replace(",", "")));
    //            createCartTable(iProductID, strProductName, strProductCode, strImagePath, dPrice, iWeight);
    //            Response.Redirect(Request.UrlReferrer.AbsolutePath, false);

    //        }else ControlUtil.LogError("Add To Shopping Cart Page ProductDetail");
    //    }
    //    catch (Exception ex)
    //    {
    //        ControlUtil.LogError("Add To Shopping Cart Page ProductDetail:"  + ex.Message.ToString());
    //    }
        
    //}
    protected void btnOrder_Command(object sender, CommandEventArgs e)
    {
        try
        {
            if (e.CommandArgument != null)//Dat hang
            {
                if (ViewState["ListProduct"] != null)
                {
                    string str = ViewState["ListProduct"].ToString();
                    string[] arrListProduct = str.Split('@');
                    int iProductID = Convert.ToInt32(arrListProduct[0]);
                    string strProductName = arrListProduct[1];
                    string strProductCode = arrListProduct[2];
                    string strImagePath = arrListProduct[3];
                    double dPrice = Convert.ToDouble(arrListProduct[4]);
                    int iWeight = Convert.ToInt32(Server.HtmlEncode(txtWeight.Text.Trim().ToString().Replace(",", "") == "" ? "0" : txtWeight.Text.Trim().ToString().Replace(",", "")));
                    string strIsPromotion = arrListProduct[5];
                    createCartTable(iProductID, strProductName, strProductCode, strImagePath, dPrice, iWeight, Convert.ToInt32(strIsPromotion));
                    Response.Redirect(Request.UrlReferrer.AbsolutePath, false);
                }

            }
            else ControlUtil.LogError("Add To Shopping Cart Page ProductDetail");
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Add To Shopping Cart Page ProductDetail:" + ex.Message.ToString());
        }
    }
}